package com.cory.boot.support.mybatis.interceptor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.core.annotation.AnnotationUtils;
import com.cory.boot.support.mybatis.annotation.CustomParam;
import com.cory.boot.utils.SpringUtils;
import com.google.common.collect.Maps;

/**
 * 自动注入自定义参数
 * @author xiongcong
 * @date 2022-04-26
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
public class CustomParamInterceptor implements Interceptor {

    @Override
    @SuppressWarnings({"rawtypes", "unchecked"})
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        String namespace = mappedStatement.getId();
        String className = namespace.substring(0, namespace.lastIndexOf("."));
        String mName  = mappedStatement.getId().substring(mappedStatement.getId().lastIndexOf(".") + 1 ,mappedStatement.getId().length());
        Method[] ms = Class.forName(className).getMethods();
        
        for (Method m : ms) {
            CustomParam annotation = m.getAnnotation(CustomParam.class);
            if (annotation != null && StringUtils.isNotBlank(annotation.name()) && m.getName().equals(mName)) {
                Map map = null;
                if (args[1] == null) {
                    //没有参数列表
                    args[1] = new MapperMethod.ParamMap<>();
                } else if(!(args[1] instanceof Map)){
                    //单参数列表时，参数数据是以具体对象形式存储，需要转成map之后才能再往里添加，这里只有值，没有参数名
                    //通过java 通过反射获取参数名称，然后生成对应的map
                    Map tempMap = new MapperMethod.ParamMap<>();
                    Parameter[] parameters = m.getParameters();
                    Parameter param  = parameters[0];
                    //第一个参数获取@Param注解，然后获取值
                    if (param.isAnnotationPresent(Param.class)){
                        String paramName = param.getAnnotation(Param.class).value();
                        tempMap.put(paramName,args[1]);
                    } else {
                        tempMap.putAll(objectToMap(args[1]));
                    }
                    args[1] = tempMap;
                }
                //如果是多参数列表时直接转map即可
                map = (Map) args[1];
                
                CustomParamHandle handle = getCustomParamHandle(annotation.name());
                if (handle != null) {
                    Map<String, Object> params = handle.custom();
                    if (params != null && params.size() > 0) {
                        map.putAll(params);
                    }
                }
                
            }
        }

        return invocation.proceed();
    }
    
    @Override
    public Object plugin(Object target) {
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }

    @Override
    public void setProperties(Properties properties) {

    }
    
    /**
     * 自定义
     */
    public static interface CustomParamHandle {
        
        Map<String, Object> custom();
        
    }
    
    private static Map<String, CustomParamHandle> customParamHandleMap;
    
    public static CustomParamHandle getCustomParamHandle(String name) {
        if (customParamHandleMap == null) {
            customParamHandleMap = Maps.newHashMap();
            
            List<CustomParamHandle> list = new ArrayList<>(SpringUtils.getContext().getBeansOfType(CustomParamHandle.class).values());
            for (CustomParamHandle handle : list) {
                CustomParam annotation = AnnotationUtils.findAnnotation(handle.getClass(), CustomParam.class);
                if (annotation != null) {
                    customParamHandleMap.put(annotation.name(), handle);
                }
            }
        }
        
        return customParamHandleMap.get(name);
    }
    
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        List<Field> fields = new ArrayList<>();
        //把父类包含的字段遍历出来
        while (clazz!=null){
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();

        }
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}
